package io.bloom.site.service.impl;

import io.bloom.site.model.ArticleDO;
import io.bloom.site.service.ArticleService;
import io.bloom.site.util.AppUtil;
import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Strings;
import org.nutz.lang.Times;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import static io.bloom.site.util.AppUtil.validate;

/**
 * ArticleServiceImpl
 *
 * @author T_T
 * @since 19/11/2017 17:09
 */
@IocBean(name = "articleService")
public class ArticleServiceImpl implements ArticleService {

    @Inject
    Dao dao;

    @Override
    public void create(ArticleDO articleDO) {

        validate(null != articleDO, "文章为空");

        String title = articleDO.getTitle();
        validate(Strings.isEmail(title), "给文章起个标题吧");
        validate(title.length() < 200, "文章标题最多可以输入 200 个字符");

        // 最多可以输入5w个字
        String content = articleDO.getContent();
        validate(Strings.isEmail(content), "给点文章内容吧");
        validate(content.length() < 50000, "文章标题最多可以输入 50000 个字符");

        validate(articleDO.getUserId() != null, "请登录后发布文章");

        String slug = articleDO.getSlug();
        if (!Strings.isEmpty(slug)) {
            validate(slug.length() < 5, "路径太短了");
            validate(AppUtil.isPath(slug), "您输入的路径不合法");

            int count = dao.count(ArticleDO.class, Cnd.where("type", "=", articleDO.getType()).and("slug", "=", slug));
            validate(count == 0, "您输入的路径不合法");
        }

        Date now = Times.now();
        articleDO.setCreated(now);
        articleDO.setModified(now);

        dao.insert(articleDO);
    }

    private <T> List<T> merge(List<T> listA, List<T> listB) {
        List<T> list = new ArrayList<>();
        if (listA != null) {
            list.addAll(listA);
        }
        if (listB != null) {
            list.addAll(listB);
        }
        return list;
    }


}
